package cn.lingyangwl.agile.misc.short_link.service.impl;

import cn.lingyangwl.agile.common.security.utils.*;
import cn.lingyangwl.agile.misc.short_link.assembly.*;
import cn.lingyangwl.agile.misc.short_link.manager.*;
import cn.lingyangwl.agile.misc.short_link.mapper.*;
import cn.lingyangwl.agile.misc.short_link.model.entity.*;
import cn.lingyangwl.agile.misc.short_link.model.rqrs.*;
import cn.lingyangwl.agile.misc.short_link.service.*;
import cn.lingyangwl.agile.model.*;
import cn.lingyangwl.framework.tool.core.exception.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author shenguangyang
 */
@Service
public class DomainServiceImpl extends ServiceImpl<SlLinkDomainMapper, LinkDomain> implements DomainService {
    @Resource
    private SlLinkDomainManager domainManager;
    @Resource
    private DomainAssembly domainAssembly;
    @Resource
    private SlShortLinkManager linkGroupManagerManager;

    @Override
    public List<LinkDomain> listDomain(DomainListReq rq) {
        LambdaQueryWrapper<LinkDomain> lqw = LinkDomain.lqw()
                .like(StringUtils.isNotEmpty(rq.getDomain()), LinkDomain::getDomain, rq.getDomain())
                .orderByDesc(BasePlusPO::getCreatedAt);
        return this.list(lqw);
    }

    @Override
    public boolean saveDomain(DomainReq rq) {
        LinkDomain linkDomain = domainAssembly.toLinkDomain(rq);
        linkDomain.setUserId(SecurityUtils.getUserId());

        if (this.count(LinkDomain.lqw().eq(LinkDomain::getDomain, rq.getDomain())) > 0) {
            throw new BizException("域名已存在");
        }
        return this.save(linkDomain);
    }

    @Override
    public boolean updateDomain(DomainReq rq) {
        LinkDomain linkDomain = domainAssembly.toLinkDomain(rq);
        linkDomain.setUserId(SecurityUtils.getUserId());
        LambdaQueryWrapper<LinkDomain> lqw = LinkDomain.lqw().eq(LinkDomain::getDomain, rq.getDomain())
                .ne(LinkDomain::getId, rq.getId());
        if (this.count(lqw) > 0) {
            throw new BizException("域名已存在");
        }
        return this.updateById(linkDomain);
    }

    @Override
    public boolean deleteDomainByIds(List<Long> ids) {
        if (linkGroupManagerManager.count(ShortLink.lqw().eq(ShortLink::getDomainId, ids)) > 0) {
            throw new BizException("已有短链引用当前域名");
        }
        return this.removeByIds(ids);
    }
}
